<?php

namespace app\award;

use app\controllers\admin\uni\finance\ProfitController;
use app\models\user\User;
use app\models\user\UserLevel;
use app\services\Chain;
use yii\helpers\ArrayHelper;

/**
 * Class Profit
 * @package app\award
 *
 * 1) 计算自己整个团队的订单数(金额)
 * 2) 计算子团队
 * 3) 自己 减去 全部团队
 *
 */
class Profit
{
    protected static $users = [];

    public static function getList()
    {
        // 找出全部合伙人
        $users = User::find()
            ->where(['new_level' => UserLevel::$keys['vip24']])
            ->select(['id'])
            ->column();

        // 处理子团队, 子合伙人
        $data = [];
        foreach ($users as $user) {
            $children = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip21'],
                UserLevel::$keys['vip22'],
                UserLevel::$keys['vip23'],
                UserLevel::$keys['vip24'],
            ], ['id']);
            $children = ArrayHelper::getColumn($children, 'id');

            $manager = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip24'],
            ], ['id']);
            $manager = ArrayHelper::getColumn($manager, 'id');

            $data[] = [
                'id' => $user,
                'children' => $children,
                'manager' => $manager,
            ];
        }

        // var_dump($data);exit;

        // 清除没有子合伙人的
        // 这里相当于, 没有manager的人要去除
        // 主要给下面去重使用
        $x = ArrayHelper::getColumn($data, 'manager');
        foreach ($x as $k => $v) {
            if (!$v) {
                unset($x[$k]);
            }
        }

        // 去子合伙人
        // 存在于别人的团队中, 就是子合伙人
        // id 存在于 别的 manager中, 肯定是子合伙人
        foreach ($users as $key => $user) {
            foreach ($x as $item) {
                if (in_array($user, $item)) {
                    unset($users[$key]);
                }
            }
        }

        // 此时已经找出最顶层的合伙人了
        // var_dump($users);exit;

        // var_dump($data);exit;
        // 此数据后面还要用, 保存到类中
        self::$users = $data;

        // 计算业绩
        // $needs = [];
        // foreach ($users as $user) {
        //     foreach ($data as $item) {
        //         if ($user == $item['id']) {
        //             $needs[] = $item;
        //             break;
        //         }
        //     }
        // }
        $needs = self::getData($users);
        $list = self::getOrder($needs);
        // var_dump($list);exit;

        // 处理佣金极差
        foreach ($list as &$item) {

            if ($item['amount'] == 0) {
                continue;
            }

            // 需要减去第1层子团队佣金
            $first_child = self::firstChild($item, $list);
            // var_dump($first_child);exit;

            $item['first_child'] = $first_child;
            $item['real_amount'] = $item['amount'] - $first_child;
        }

        return $list;
    }

    // 为了少查数据库, 获取相应数据
    private static function getData($users)
    {
        $needs = [];
        foreach ($users as $user) {
            foreach (self::$users as $item) {
                if ($user == $item['id']) {
                    $needs[] = $item;
                    break;
                }
            }
        }
        return $needs;
    }

    private static function getOrder($users, $list = [])
    {
        // var_dump($users);exit;

        foreach ($users as $user) {
            // 总业绩
            $total = ProfitController::_total(array_merge([$user['id']], $user['children']), 2);
            if (!key_exists($user['id'], $list)) {
                $list[$user['id']] = $user;
                $list[$user['id']]['total'] = $total;
                // 获取对应的佣金
                $x = ProfitController::_amount($total);
                $list[$user['id']]['amount'] = $x[0];
                $list[$user['id']]['ratio'] = $x[1];
            }

            // 操作子团队业绩
            if (!empty($user['manager'])) {
                $manager = self::getData($user['manager']);
                $list = self::getOrder($manager, $list);
            }
        }

        return $list;
    }

    // 第1层子团队处理
    private static function firstChild($child, $users)
    {
        $sum = 0;

        foreach ($child['manager'] as $id) {

            // 找出第1个满足等级的推荐人
            $first = Chain::getFirstReferrerChainId($id, [
                UserLevel::$keys['vip24']
            ]);

            // 如果第1个推荐人, 刚好是$child,
            // 则说明 此子合伙人是 $child的第1层 子团队
            if ($first && $first['id'] == $child['id']) {
                if (isset($users[$id]) && isset($users[$id]['amount'])) {
                    $sum += $users[$id]['amount'];
                }
            }
        }

        return $sum;
    }
}